from django.views import View
from .custome_response import FlyResponse
from .utils import model_to_dict
from django.db.models import Q
from django.core.paginator import Paginator
from . import const

class FliyView(View):
    form_class=None
    module_class=None
    filter_field=()

    def post(self,request):
        form = self.form_class(request.POST)
        if form.is_valid():
            form.save() #直接能保存到数据库
            return FlyResponse()

        return FlyResponse(code=-1, msg=form.error_msg)

    def delete(self,request):
        id=request.GET.get("id")
        if not id:
            return FlyResponse(-1,"请传入要删除的id")

        obj=self.module_class.objects.filter(id=id)
        if not obj.exists():
            # ret = {"code": -1, "msg": "要删除的数据不存在"}
            # return JsonResponse(ret)
            return FlyResponse(-1,"要删除的数据不存在 ")
        obj.delete()
        # ret={"code":-1,"msg":"删除成功"}
        # return JsonResponse(ret)
        return FlyResponse()

    def put(self, request):  # 修改数据
        # print(request.GET)
        # print(request.POST)
        print("request.PUT", request.PUT)
        print(request.PUT.get("id"))
        print("request.FILES", request.FILES)
        id = request.PUT.get("id")
        if not id:
            # ret={"code":-1,"msg":"请传入要修改的id"}
            # return HttpResponse("ret")
            return FlyResponse(-1, "请传入要修改的id")
        obj = self.module_class.objects.filter(id=id)
        if not obj.exists():
            # ret={"code": -1, "msg": "要修改的数据不存在"}
            # return JsonResponse(ret)
            return FlyResponse(-1, "要修改的id不存在")

        form = self.form_class(request.PUT, instance=obj.first())
        if form.is_valid():
            form.save()
            # ret={"code":0,"msg":"操作成功"}
            # return JsonResponse(ret)
            return FlyResponse()

        # ret={"code":-1,"msg":form.error_msg}
        # return JsonResponse(ret)
        return FlyResponse(code=-1, msg=form.error_msg)


    def get(self,request):
        if not self.check_page_param():
            return FlyResponse(-1, "分页信息不正确")
        query_set = self.get_filter_query_set() #获取筛选的结果
        q_obj = self.get_search_obj()  # 获取模糊查询的条件
        data = query_set.filter(q_obj)
        data_list = [] #报错的是所有的数据
        limit, page = self.check_page_param() #获取分页limit和页数
        paginator = Paginator(data, limit)
        page_data = paginator.page(page)
        for query in page_data:
            data_list.append(model_to_dict(query))
        return FlyResponse(data=data_list, count=paginator.count)